package com.yimixian.app;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.yimixian.app.address.BaiduMapUtilByRacer;
import com.yimixian.app.address.LocationBean;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocatedListener2;
import com.yimixian.app.location.LocationProvider;

import org.litepal.LitePalApplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import java.util.List;

public class YMXApplication extends LitePalApplication {
    private static YMXApplication mInstance = null;
    public SharedPreferences mSharedPreferences;

    public long responseTime;//http头部的时间 转换为秒
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;
    public LocatedListener locatedListener;
    public LocatedListener2 locatedListener2;
    public boolean needGeoPoiInfo;
    public boolean needGeoPoiInfo2;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.SAVE_CRASH_LOG) {
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }
        SDKInitializer.initialize(getApplicationContext());
        mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS_NAME,
                Context.MODE_PRIVATE);
        mInstance = this;
        mLocationClient = new LocationClient(this.getApplicationContext());
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);

    }

    public void startAppService(){
        startService(new Intent(this, AppService.class));
    }

    public void stopAppService(){
        stopService(new Intent(this, AppService.class));
    }


    public static YMXApplication getInstance() {
        return mInstance;
    }

    public void setLocatedListener(boolean needGeoPoiInfo, LocatedListener locatedListener) {
        this.locatedListener = locatedListener;
        this.needGeoPoiInfo = needGeoPoiInfo;
    }

    public void setLocatedListener2(boolean needGeoPoiInfo, LocatedListener2 locatedListener) {
        this.locatedListener2 = locatedListener;
        this.needGeoPoiInfo2 = needGeoPoiInfo;
    }

    /**
     * 实现实时位置回调监听
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            /**
             * 根据当前一米App需求，定位成功只存在有网络的情况，其他定位成功（离线， GPS）暂不考虑
             */
            if (location.getLocType() == BDLocation.TypeServerError ||
                    location.getLocType() == BDLocation.TypeNetWorkException ||
                    location.getLocType() == BDLocation.TypeCriteriaException) {
                //"服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因"
                //网络不同导致定位失败，请检查网络是否通畅
                //无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机
                if (locatedListener != null) {
                    locatedListener.locatedFailedListener();
                    locatedListener = null;
                }
            }else{
                if (!needGeoPoiInfo2){
                    if (locatedListener2 != null) {
                        locatedListener2.locatedSuccessListener(location);
                        locatedListener2 = null;
                    }
                }
                if (needGeoPoiInfo){
                    reverseGeoCode(new LatLng(location.getLatitude(), location.getLongitude()));
                    needGeoPoiInfo = false;
                }else{
                    if (locatedListener != null) {
                        locatedListener.locatedSuccessListener(location);
                        locatedListener = null;
                    }
                }
            }
            LocationProvider.getInstance().stopBaiduLocated();
        }
    }

    /**
     * 通过经纬度 获取兴趣点
     * @param ll
     */
    public void reverseGeoCode(LatLng ll) {
        BaiduMapUtilByRacer.getPoisByGeoCode(ll.latitude, ll.longitude,
                new MyGeoCodePoiListener());
    }

    class MyGeoCodePoiListener implements BaiduMapUtilByRacer.GeoCodePoiListener {
        @Override
        public void onGetSucceed(LocationBean locationBean,
                                 List<PoiInfo> poiList) {
            if (locatedListener == null) return;
            if (poiList != null && poiList.size() > 0){
                DataManager.getInstance().put(CacheKeys.CURRENT_POSITION_CITY,
                        locationBean.city);
                poiList.get(0).city = locationBean.city;
                locatedListener.locatedSuccessGeoPoiInfoListener(poiList.get(0));
            }else{
                locatedListener.locatedFailedGeoPoiInfoListener();
            }
        }

        @Override
        public void onGetFailed() {
            if (locatedListener != null) {
                locatedListener.locatedFailedGeoPoiInfoListener();
            }
        }
    }
}
